import argparse
import torch
import os
import json
from tqdm import tqdm
import shortuuid

from dattn.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from dattn.model.builder import load_pretrained_model
from dattn.utils import disable_torch_init
from dattn.dataset.vis_utils import process_images, get_model_name_from_path
from dattn.dataset.txt_utils import tokenizer_image_token, preprocess_chat

from PIL import Image


import pandas as pd
from PIL import Image
import os


def eval_model(args):
    # Model
    disable_torch_init()
    model_path = os.path.expanduser(args.model_path)
    model_name = get_model_name_from_path(model_path)
    model, tokenizer, image_processor = load_pretrained_model(model_path)
    
    benchmark_dir = os.path.join(args.directory, 'Questions.csv')
    # Load and read the CSV
    df = pd.read_csv(benchmark_dir)  # Assuming the fields are separated by tabs
    answers_file = os.path.expanduser(args.answers_file)
    # Check if the directory is specified in the path
    if os.path.dirname(answers_file):
        # Create the directory if it doesn't exist
        os.makedirs(os.path.dirname(answers_file), exist_ok=True)

    # Now open the file
    ans_file = open(answers_file, "w")
    num_correct, num_total = 0, 0
    index, round_correct = 0, 0
    # Loop through each row in the DataFrame
    for i, row in tqdm(df.iterrows(), total=len(df)):
        # Construct the 'prompts' string

        opts = row['Options'].split(' ')
        cur_prompt = f"{row['Question']}\nA. {opts[1]}\nB. {opts[3]}\n"
        qs = cur_prompt + "Answer only with the option's letter A or B from the given choices directly."
        qs = DEFAULT_IMAGE_TOKEN + '\n' + qs

        prompt = preprocess_chat([{"from": "human", "value": qs}], tokenizer)

        input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()

        photo_id = i+1
        image_path = os.path.join(args.directory, 'MMVP Images', f"{photo_id}.jpg")
        image = Image.open(image_path)
        image_tensor = process_images([image], image_processor, model.config)[0]

        with torch.inference_mode():
            output_ids = model.generate(
                input_ids,
                images=image_tensor.unsqueeze(0).half().cuda(),
                image_sizes=[image.size],
                do_sample=True if args.temperature > 0 else False,
                temperature=args.temperature,
                top_p=args.top_p,
                num_beams=args.num_beams,
                # no_repeat_ngram_size=3,
                max_new_tokens=4096,
                pad_token_id=tokenizer.pad_token_id,
                use_cache=True)
            outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip().lower()

        # assert len(outputs) == 1, outputs
        # assert outputs in ('a', 'b'), outputs

        index += 1
        if outputs == row["Correct Answer"][1]:
            round_correct += 1
        if index == 2:
            index = 0
            if round_correct == 2:
                num_correct += 1
            round_correct = 0
            num_total += 1

        ans_id = shortuuid.uuid()
        ans_file.write(json.dumps({"question_id": photo_id,
                                   "prompt": cur_prompt,
                                   "answer": row["Correct Answer"], 
                                   "response": outputs,
                                   "answer_id": ans_id,
                                   "model_id": model_name,
                                   }) + "\n")
        ans_file.flush()
    
    print(f"The accuracy is {num_correct/num_total*100:.2f}%")
    ans_file.write(json.dumps({
        'num_correct': num_correct,
        'num_total': num_total,
        'accuracy': num_correct/num_total
    }) + '\n')

    ans_file.close()

            

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-path", type=str, required=True, default=None)
    parser.add_argument("--directory", type=str, default="")
    parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
    parser.add_argument("--answers-file", type=str, default="answer.jsonl")
    parser.add_argument("--temperature", type=float, default=0.2)
    parser.add_argument("--top_p", type=float, default=None)
    parser.add_argument("--num_beams", type=int, default=1)
    args = parser.parse_args()

    eval_model(args)